package com.netease.xone.fragment;

import java.util.LinkedList;

import media.MediaRecorderWrapper;
import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.LoopBack;
import protocol.transactions.TransactionUpload.UploadPrama;
import Utils.StackTraceUtil;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.netease.framework.widget.CustomAlertDialog;
import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts;
import com.netease.pkgRelated.XoneConsts.MENU_ID;
import com.netease.xone.R;
import com.netease.xone.dataMgr.ModelDiscuss;
import com.netease.xone.dataMgr.ParcelableArgument;
import com.netease.xone.itemview.ItemViewTipBase;
import com.netease.xone.widget.DiscussEditWrapper;
import com.netease.xone.widget.DiscussEditWrapper.ViewTag;
import com.netease.xone.widget.DiscussEmoticonWrapper;

public class FragmentDiscuss extends FragmentBase {
    public static final String TAG = FragmentDiscuss.class.getSimpleName();
    
    /**
     * 目的是为了在非前台时不处理back按钮
     */
    private boolean bVisible = true;
	private String mId = ""; 
	
	private ParcelableArgument mArgument;
	private View mRootView = null;
	private DiscussEditWrapper mDiscussEditWrapper;
	private DiscussEmoticonWrapper mEmoteViewWrapper;
	
	private LinearLayout mCfContainer;
	private CheckBox mCheckBox;
	private TextView mLabel;
	private ModelDiscuss mModelDiscuss;
	
	public static FragmentDiscuss newInstance(Parcelable obj) {
		FragmentDiscuss f = new FragmentDiscuss();
		Bundle b = new Bundle();
		b.putParcelable("obj", obj);
		f.setArguments(b);
		return f;
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
	    NTLog.d(TAG, StackTraceUtil.getMethodName()
                + " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
        super.onCreate(savedInstanceState);
        /**
         * 一定要设置为true,才会调用onCreateOptionsMenu
         */
        setHasOptionsMenu(true);
        
        mArgument = getArguments().getParcelable("obj");
        XoneService.getInstance().addListener(mXoneCallBack);
        XoneService.getInstance().doUserInputTipList("2");
        XoneService.getInstance().doSourceInputTipList("2");
        XoneService.getInstance().doTopicInputTipList();
        XoneService.getInstance().doSubjectInputTipList();
//        ManagerDiscussTip.insertTest();
    }
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
	    NTLog.d(TAG, StackTraceUtil.getMethodName()
                + " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
		mId = String.valueOf(System.currentTimeMillis());
		mRootView = inflater.inflate(R.layout.fragment_discuss, container, false);
		bindView(mRootView);
		
		return mRootView;
	}
	
	private void bindView(View view) {
	    mDiscussEditWrapper = new DiscussEditWrapper(this, (ViewGroup)mRootView);
        mEmoteViewWrapper = new DiscussEmoticonWrapper(this, (ViewGroup)mRootView, mId);
        mDiscussEditWrapper.setOnButtonClickListener(mEmoteViewWrapper.getOnButtonClickListener());
		mEmoteViewWrapper.setOnButtonClickListener(mDiscussEditWrapper.getOnButtonClickListener());
		mEmoteViewWrapper.setOnEmoticonClickListener(mDiscussEditWrapper.getEmoticonClickListener());
		
		mCfContainer = (LinearLayout)mRootView.findViewById(R.id.emote_cf_container);
		mCfContainer.setVisibility(View.GONE);
		mCheckBox = (CheckBox)mCfContainer.findViewById(R.id.emote_check);
		mLabel = (TextView)mCfContainer.findViewById(R.id.emote_check_label);
	}
	
	@Override
	public void onResume() {
	    NTLog.d(TAG, StackTraceUtil.getMethodName());
	    super.onResume();
	    /**
	     * 设置title显示,设置最大输入字符数和提示剩余字符数
	     */
	    if (null != mArgument) {
	        switch (mArgument.getType()) {
	            case ParcelableArgument.TYPE_DEFAULT:
	                getSherlockActivity().getSupportActionBar().setTitle(R.string.discuss_type_default);
	                mDiscussEditWrapper.TEXT_MAX_LENGTH = 2000;
	                mDiscussEditWrapper.mRemainTextLen = 100;
	                break;
	            case ParcelableArgument.TYPE_FORWARD:
	                getSherlockActivity().getSupportActionBar().setTitle(R.string.discuss_type_forward);
	                mDiscussEditWrapper.TEXT_MAX_LENGTH = 163;
                    mDiscussEditWrapper.mRemainTextLen = 20;
	                mCfContainer.setVisibility(View.VISIBLE);
	                mLabel.setText(R.string.discuss_check_comment);
	                break;
	            case ParcelableArgument.TYPE_COMMENT:
	                getSherlockActivity().getSupportActionBar().setTitle(R.string.discuss_type_comment);
	                mDiscussEditWrapper.TEXT_MAX_LENGTH = 163;
                    mDiscussEditWrapper.mRemainTextLen = 20;
	                mCfContainer.setVisibility(View.VISIBLE);
	                mLabel.setText(R.string.discuss_check_forward);
	                break;
	            default:
	                break;
	        }
	    }
	    bVisible = true;
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
	    NTLog.d(TAG, StackTraceUtil.getMethodName());
	    
	    com.actionbarsherlock.view.MenuItem item = menu.add(Menu.NONE, MENU_ID.menu_discuss_send, 0, "done");
	    item.setIcon(R.drawable.icon_action_done_selector);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        
        if (MediaRecorderWrapper.getInstance().isRecord()) {
            item.setEnabled(false);
        } else {
            item.setEnabled(true);
        }
        
	    super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
	    NTLog.d(TAG, StackTraceUtil.getMethodName());
	    switch (item.getItemId()) {
            case MENU_ID.menu_discuss_send:
                boolean bRes = needSend();
                if (bRes) {
                    send();
                    getActivity().finish();
                } else {
                    showToast(R.string.discuss_msg_null);
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
	}
	
	@Override
	protected void onLeftTopBack() {
	    if (MediaRecorderWrapper.getInstance().isRecord()) {
	        MediaRecorderWrapper.getInstance().stop();
	    }
	    onBackPressed();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	    NTLog.d(TAG, StackTraceUtil.getMethodName());
	    super.onCreateContextMenu(menu, v, menuInfo);
		if (null != mEmoteViewWrapper) {
			mEmoteViewWrapper.onCreateContextMenu(menu, v, menuInfo);
		}
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    NTLog.d(TAG, StackTraceUtil.getMethodName());
		boolean bRes = false;
		if (null != mEmoteViewWrapper) {
			bRes = mEmoteViewWrapper.onContextItemSelected(item);
		}
		
		if (bRes) {
			return bRes;
		}
		
		return super.onContextItemSelected(item);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    NTLog.d(TAG, StackTraceUtil.getMethodName());
		boolean bRes = false;
		do {
			
			if (null != mDiscussEditWrapper) {
				bRes = mDiscussEditWrapper.onActivityResult(requestCode, resultCode, data);
			}
			
			if (bRes) {
				break;
			}
			
			if (null != mEmoteViewWrapper) {
				bRes = mEmoteViewWrapper.onActivityResult(requestCode, resultCode, data);
			}
			
			if (bRes) {
				break;
			}
		} while(false);
	}
	
	@Override
	public void onPause() {
	    bVisible = false;
	    super.onPause();
	}
	
	/**
	 * 判断是否有内容需要发送
	 * @return
	 */
	private boolean needSend() {
	    boolean bRes = false;
	    
	    do {
	        EditText editText = (EditText)mRootView.findViewById(R.id.send_edit_postmessage);
	        if (TextUtils.isEmpty(editText.getText().toString()) && mArgument.getType() == ParcelableArgument.TYPE_FORWARD) {
	            bRes = true;
                break;
	        }
	        
	        if (!TextUtils.isEmpty(editText.getText().toString())) {
	            bRes = true;
	            break;
	        }
	        
	        if (View.VISIBLE == mRootView.findViewById(R.id.discuss_media).getVisibility()) {
	            bRes = true;
                break;
	        }
	    } while(false);
	    
	    if (bRes) {
	        mModelDiscuss = new ModelDiscuss(-1);
	        Object obj = null;
	        
	        mModelDiscuss.type = mArgument.getType();
	        
	        EditText editText = (EditText)mRootView.findViewById(R.id.send_edit_postmessage);
	        mModelDiscuss.content = editText.getText().toString();
	        
	        obj = mRootView.findViewById(R.id.discuss_voice_anim).getTag();
	        if (null != obj && obj instanceof ViewTag) { 
	            mModelDiscuss.recorder = ((ViewTag)obj).path;
	            mModelDiscuss.duration = ((ViewTag)obj).duration;
	        }
	        
	        obj = mRootView.findViewById(R.id.picture).getTag();
	        if (null != obj && obj instanceof ViewTag) {
	            mModelDiscuss.image = ((ViewTag)obj).path;
	        }
	        mModelDiscuss.infoId = mArgument.mInfoId;
	        mModelDiscuss.flag = mCheckBox.isChecked();
	        
	    }
	    
	    return bRes;
	}
	
	private void send() {
	    new UploadRunnable(mModelDiscuss).run();
	}
	
	/**
	 * 点击返回键时的处理函数
	 * @return
	 */
	public boolean onBackPressed() {
        boolean bRes = false;
        if (bVisible && needSend()) {
            CustomAlertDialog.showAlertDialog(getSherlockActivity(), 
                    0, 
                    R.string.discuss_dialog_title, 
                    R.string.discuss_dialog_content, 
                    -1, 
                    R.string.discuss_dialog_positive, 
                    R.string.discuss_dialog_nagetive, 
                    new CustomAlertDialog.DialogListener(){

                        @Override
                        public void onClick(DialogInterface DialogListn, int which, int key,
                                View view) {
                            if (which == DialogInterface.BUTTON_POSITIVE) {
                                //TODO 调用保持草稿接口
                                mModelDiscuss.save();
                            } else {
                                DiscussEmoticonWrapper.delCacheFile(mId);
                            }
                            
                            getActivity().finish();
                        }
            });
            return true;
        } else if (bVisible && !needSend()) {
            getActivity().finish();
            return true;
        }
        
        return bRes;
    }

	@Override
	public void onDestroy() {
	    NTLog.d(TAG, StackTraceUtil.getMethodName());
		super.onDestroy();
		XoneService.getInstance().removeListener(mXoneCallBack);
        mXoneCallBack = null;
		mRootView = null;
		if (null != mDiscussEditWrapper) {
			mDiscussEditWrapper.clear();
		}
		mDiscussEditWrapper = null;
		
		if (null != mEmoteViewWrapper) {
			mEmoteViewWrapper.clear();
		}
		mEmoteViewWrapper = null;
		
	}
	
	
	private XoneCallBack mXoneCallBack = new XoneCallBack() {
	    @Override
        public void onLoopBack(int transactionId, Object obj) {
	        if (null == obj) {
	            return;
	        }
	        
	        if (obj instanceof LoopBack) {
	            if (((LoopBack)obj).mType >= ItemViewTipBase.TYPE_USER 
	                    && ((LoopBack)obj).mType <= ItemViewTipBase.TYPE_SUBJECT) {
	                mDiscussEditWrapper.getEmoticonClickListener().onClick((String)((LoopBack)obj).mData);
	            } else if (XoneConsts.RESULT_IMAGE_RECORDER == ((LoopBack)obj).mType) {
	                Intent data = new Intent();
	                ViewTag tag = (ViewTag)((LoopBack)obj).mData;
	                data.putExtra(XoneConsts.EXTRA_PATH, tag.path);
	                data.putExtra(XoneConsts.EXTRA_OPERATE, tag.flag);
	                data.putExtra(XoneConsts.EXTRA_DURATION, tag.duration);
	                onActivityResult(XoneConsts.RESULT_IMAGE_RECORDER, Activity.RESULT_OK, data);
	            }
	        }
	    };
	};
	
	public enum State {  
        IMAGE, AUDIO, CONTENT
    }; 
    
    /**
     * 发送消息给资讯界面显示
     * @param value
     */
    private void sendAppMsg(String value) {
        LoopBack lookBack = null;
        lookBack = new LoopBack();
        lookBack.mType = TAG.hashCode();
        lookBack.mData = value;
        XoneService.getInstance().doLoopBack(lookBack);
    }
    
	private class UploadRunnable implements Runnable {
	     
	    
	    private State state = State.IMAGE;
	    
	    private int    mImageId = -1;
	    private int    mAudioId = -1;

	    private String mImageUrl = null;
	    private String mAudioUrl = null;
	    
	    private LinkedList<Integer> mReqList = new LinkedList<Integer>();
	    private ModelDiscuss mModelDiscuss;
	
	    public UploadRunnable(ModelDiscuss model) {
	        mModelDiscuss = model;
	        
	        XoneService.getInstance().addListener(mXoneCallBack);
            sendAppMsg(getString(R.string.discuss_msg_doing));
	    }
	    
        @Override
        public void run() {
            int tid = 0;
            String content = null;
            UploadPrama prama = null;
            
            switch (state) {
                case IMAGE:
                    if (TextUtils.isEmpty(mModelDiscuss.image)) {
                        state = State.AUDIO;
                        run();
                        break;
                    }
                    prama = new UploadPrama();
                    prama.type = UploadPrama.TYPE_IMAGE;
                    prama.path = mModelDiscuss.image;
                    mImageId = XoneService.getInstance().doUpload(prama);
                    break;
                case AUDIO:
                    if (TextUtils.isEmpty(mModelDiscuss.recorder)) {
                        state = State.CONTENT;
                        run();
                        break;
                    }
                    prama = new UploadPrama();
                    prama.type = UploadPrama.TYPE_AUDIO;
                    prama.duration = mModelDiscuss.duration;
                    prama.path = mModelDiscuss.recorder;
                    mAudioId = XoneService.getInstance().doUpload(prama);
                    break;
                case CONTENT:
                    if (mModelDiscuss.type == ParcelableArgument.TYPE_DEFAULT) {
                        prama = new UploadPrama();
                        prama.duration = mModelDiscuss.duration;
                        prama.path = mAudioUrl;
                        tid = XoneService.getInstance().doPostDiscuss(mModelDiscuss.content, mImageUrl, prama);
                        mReqList.add(tid);
                    } else if (mModelDiscuss.type == ParcelableArgument.TYPE_COMMENT) {
                        prama = new UploadPrama();
                        
                        prama.infoId = mModelDiscuss.infoId;
                        prama.flag = mModelDiscuss.flag;
                        
                        content = mModelDiscuss.content;
                        if (!TextUtils.isEmpty(mImageUrl)) {
                            content += " [图:" + mImageUrl + "]";
                        }
                        
                        if (!TextUtils.isEmpty(mAudioUrl)) {
                            content += " [音:" + mAudioUrl + "]";
                        }
                        
                        tid = XoneService.getInstance().doCommentInfo(content, null, prama);
                        mReqList.add(tid);
                    } else if (mModelDiscuss.type == ParcelableArgument.TYPE_FORWARD) {
                        prama = new UploadPrama();
                        
                        prama.infoId = mModelDiscuss.infoId;
                        prama.flag = mModelDiscuss.flag;
                        
                        content = mModelDiscuss.content;
                        if (!TextUtils.isEmpty(mImageUrl)) {
                            content += "[图:" + mImageUrl + "]";
                        }
                        
                        if (!TextUtils.isEmpty(mAudioUrl)) {
                            content += "[音:" + mAudioUrl + "]";
                        }
                        
                        tid = XoneService.getInstance().doForwardInfo(content, null, prama);
                        mReqList.add(tid);
                    }
                   
                    break;
                default:
                    break;
            }
        }
	    
        private XoneCallBack mXoneCallBack = new XoneCallBack() {
            @Override
            public void onUpload(int transactionId, Object obj) {
                if (mImageId == transactionId) {
                    mImageId = -1;
                    mImageUrl = (String)obj;
                    state = State.AUDIO;
                    run();
                } else if (mAudioId == transactionId) {
                    mAudioId = -1;
                    mAudioUrl = (String)obj;
                    state = State.CONTENT;
                    run();
                }
            };
            
            @Override
            public void onUploadError(int transactionId, int errCode, String err) {
                boolean res = false;
                if (mImageId == transactionId) {
                    mImageId = -1;
                    res = true;
                } else if (mAudioId == transactionId) {
                    mAudioId = -1;
                    res = true;
                    
                }
                
                if (res) {
                    mModelDiscuss.save();
                    if (mModelDiscuss.type == ParcelableArgument.TYPE_DEFAULT) {
                        sendAppMsg(getString(R.string.discuss_msg_fail));
                    } else if (mModelDiscuss.type == ParcelableArgument.TYPE_COMMENT) {
                        sendAppMsg(getString(R.string.discuss_comment_fail));
                    } else if (mModelDiscuss.type == ParcelableArgument.TYPE_FORWARD) {
                        sendAppMsg(getString(R.string.discuss_forward_fail));
                    }
                }
            };
            
            @Override
            public void onPostDiscuss(int transactionId, Object obj) {
                if (mReqList.remove(Integer.valueOf(transactionId))) {
                    sendAppMsg(getString(R.string.discuss_msg_ok));
                    XoneService.getInstance().removeListener(mXoneCallBack);
                    mXoneCallBack = null;
                    DiscussEmoticonWrapper.delCacheFile(mId);
                    mId = null;
                }
            };
            
            @Override
            public void onPostDiscussError(int transactionId, int errCode, String err) {
                if (mReqList.remove(Integer.valueOf(transactionId))) {
                    sendAppMsg(getString(R.string.discuss_msg_fail));
                    mModelDiscuss.save();
                    XoneService.getInstance().removeListener(mXoneCallBack);
                    mXoneCallBack = null;
                }
            };
            
            @Override
            public void onCommentInfo(int transactionId, Object obj) {
                if (mReqList.remove(Integer.valueOf(transactionId))) {
                    sendAppMsg(getString(R.string.discuss_comment_ok));
                    XoneService.getInstance().removeListener(mXoneCallBack);
                    mXoneCallBack = null;
                    DiscussEmoticonWrapper.delCacheFile(mId);
                    mId = null;
                }
            };
            
            @Override
            public void onCommentInfoError(int transactionId, int errCode, String err) {
                if (mReqList.remove(Integer.valueOf(transactionId))) {
                    sendAppMsg(getString(R.string.discuss_comment_fail));
                    mModelDiscuss.save();
                    XoneService.getInstance().removeListener(mXoneCallBack);
                    mXoneCallBack = null;
                }
            };
            
            @Override
            public void onForwardInfo(int transactionId, Object obj) {
                if (mReqList.remove(Integer.valueOf(transactionId))) {
                    sendAppMsg(getString(R.string.discuss_forward_ok));
                    XoneService.getInstance().removeListener(mXoneCallBack);
                    mXoneCallBack = null;
                    DiscussEmoticonWrapper.delCacheFile(mId);
                    mId = null;
                }
            };
            
            @Override
            public void onForwardInfoError(int transactionId, int errCode, String err) {
                if (mReqList.remove(Integer.valueOf(transactionId))) {
                    sendAppMsg(getString(R.string.discuss_forward_fail));
                    mModelDiscuss.save();
                    XoneService.getInstance().removeListener(mXoneCallBack);
                    mXoneCallBack = null;
                }
            };
        };
	}
	
}
